//
//  DWJOAuthViewController.swift
//  weibo
//
//  Created by 代伟佳 on 16/4/17.
//  Copyright © 2016年 代伟佳. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


class DWJOAuthViewController: UIViewController {

    
    // https://api.weibo.com/oauth2/authorize
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
        // 定义一个url
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
//        print(url)
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
     
        setUpUI()
        setUpNav()

    }
    
    
    // MARK: - 监听方法
    @objc private func cancle() {
    
        SVProgressHUD.dismiss()

        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func auto() {
    
        // document.getElementById('userId').value = '18603297713'; document.getElementById('passwd').value = 'xin1314'
        
//        print("自动填充")
        // JS 注入
        let jsString = "document.getElementById('userId').value = '\(DWJweiboName)'; document.getElementById('passwd').value = '\(DWJweiboPasswd)'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        

    }
    
    
    // 设置视图
    private func setUpUI() {
    
        view.backgroundColor = UIColor.whiteColor()
    }
    
    private func setUpNav() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancle")

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
        
        navigationItem.title = "微博登录"
    }
    
    
    
    // MARK: - 懒加载控件
    private lazy var webView: UIWebView = {

        let web = UIWebView()

        return web
    }()
    
    

}
        extension DWJOAuthViewController: UIWebViewDelegate {

    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    // webView将要加载url的时候会调用 如果我们不识闲这个方法 默认返回true 如果返回false将不再加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 判断是否是我们的回调页
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(REDIRECT_URI) {
        
            // 拿到我们的请求参数request.URL?.absoluteString
            
            // 判断我们的request的请求参数是否存在
            if let q = request.URL?.query {
            
                // 获取code
                let code = q.substringFromIndex("code=".endIndex)
                
                getUserAccount(code)
            }
            
            
        }
        return true
    }
}
// MARK: - 请求access_Token
extension DWJOAuthViewController {

    // 请求access_Token
    func getUserAccount(code: String) {
        
        // 请求url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let paramaters = [
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI
            
        ]
        
        DWJNetWorkTools.sharedTools.request(.POST, urlString: urlString, params: paramaters) { (response, error) -> () in
            
            if error != nil {
            
                print("错误\(error)")
                return
            }
            
//            print(response)
            
            guard let dataDict = response as? [String: AnyObject] else {
            
                return
            }
            let account = DWJUserAccount(dict: dataDict)
//            print(account)
            
            self.getUserInfo(account)
        }

        /*
        client_id	true	string	申请应用时分配的AppKey。
        client_secret	true	string	申请应用时分配的AppSecret。
        grant_type	true	string	请求的类型，填写authorization_code
        
        grant_type为authorization_code时
        必选	类型及范围	说明
        code	true	string	调用authorize获得的code值。
        redirect_uri	true	string
        */
    }
    
    
    func getUserInfo(account: DWJUserAccount) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let paramaters = [
            "access_token":account.access_token!,
            "uid":account.uid!
        ];
        
        DWJNetWorkTools.sharedTools.request(DWJRequestMethod.GET, urlString: urlString, params: paramaters) { (response, error) -> () in
        
            if error != nil {
            
                print(error)
                return
            }

            // 判断可选值
            guard let dataDict = response as? [String: AnyObject] else {
            
                return
            }
            
            // 对我们的头像昵称赋值
            account.screen_name = dataDict["screen_name"] as? String
            account.avatar_large = dataDict["avatar_large"] as? String
//            print(account )
            
            // 保存用户数据
            DWJUersAccountTools.sharedTools.saveUserAccount(account)
            
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
            
                // 发送通知
            NSNotificationCenter.defaultCenter().postNotificationName("switchDeflutVcNSNotification", object: nil)
            })

        }
        
    }
    
    
}